package com.xxgc.cloud.springcloudgateway.route;

import cn.hutool.core.util.StrUtil;
import com.xxgc.cloud.springcloudgateway.config.SwaggerProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @program: SpringCloudStudy
 * @description: token校验
 * @author: Mr.abel(ShiJiaYi)
 * @create: 2022-11-28 21:29
 **/
//GatewayFilter 局部过滤器
@Component
@Slf4j
public class TokenFilter implements GatewayFilter, Ordered {

    /**
     * 进行token验证(放开swagger)
     * @param exchange
     * @param chain
     * @return
     */
    //过滤的方法
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //放开swagger
        String s = request.getPath().toString();
        if(s.indexOf(SwaggerProvider.SWAGGER2URL) != -1){
            return chain.filter(exchange);//放行
        }

        HttpHeaders headers = request.getHeaders();
        //从请求头部获取token
        String token = headers.getFirst(HttpHeaders.AUTHORIZATION);
        //如果token为空
        if(StrUtil.hasBlank(token)){
            //设置一个未授权的状态
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);//放行
    }

    //Order值越小，过滤器级别越高
    @Override
    public int getOrder() {
        return 99;
    }
}